<?php

/**
 * Предприятие
 *
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfPropelFormTemplate.php 10377 2008-07-21 07:10:32Z dwhittle $
 */
class FoldersForm extends BaseMaterialForm {
	public function configure() {
		
		unset ( $this ['created_at'], 
		$this ['updated_at'], 
		$this ['click'], 
		$this ['country'], 
		$this ['custom_char2'], 
		$this ['custom_file2'], 
		$this ['custom_file3'], 
		$this ['stat'] 
		 );
		
		$c = new Criteria ( );	
		$c->addAnd ( FolderPeer::TREE_PARENT, 1, Criteria::NOT_EQUAL );
		$c->addAnd ( MaterialPeer::ID, 'tt' );
		
		
		$this->setWidgets ( array (
		'id' => new sfWidgetFormInputHidden( ), 
		'user_id' => new sfWidgetFormInputHidden (  array (), array ('value' => sfContext::getInstance()->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ), 'class' => 'test' )),	  	  
	  	'separator_2' =>  new sfWidgetSeparator(array(),array('title'=>'Информация о предприятии')),			
		
  	    'mat2_folder_list' => new sfWidgetFormPropelChoiceMany ( array ('model' => 'Folder', 
  	                                                                  'multiple' => true,
  	                                                                  'expanded' => true,
  		                                                              'renderer_options' => array('formatter' =>array($this,'myFormatter')),
  	                                                                  'criteria' => $c ) )

		) );

		
		
		 /*
		  * 'separator_1' =>  new sfWidgetSeparator(array(),array('title'=>'Контактное лицо')),	
	  	  'contact_fio' =>  new sfWidgetFormInput(array(),array('size'=>'60')),	
	  	  'contact_dolzhnost' =>  new sfWidgetFormInput(array(),array('size'=>'60')),
	  	  'contact_email' =>  new sfWidgetFormInput(array(),array('size'=>'60')),
	  	  'contact_phone' =>  new sfWidgetFormInput(array(),array('size'=>'60')),
		  */
		
	     ////Для админа
		 if(sfContext::getInstance()->getUser()->hasCredential('admin'))
		 {
		 	
		 	  	  $this->widgetSchema['see'] =  new sfWidgetFormInput ( array (), array ('size' => '5' ) );
  	              $this->widgetSchema['rating'] = new sfWidgetFormInput ( array (), array ('size' => '5' ) );
  	              $this->widgetSchema['pub'] = new sfWidgetFormInputCheckbox ( );
		 	
		 }		
		 ///
		 
		
	      ////SEO теги
		 if(sfContext::getInstance()->getUser()->hasCredential('optimizator'))
		 {
		 	
		 	  	  $this->widgetSchema['seo_title'] =  new sfWidgetFormInput(array(),array('style'=>'width:200px'));
  	              $this->widgetSchema['seo_description'] = new sfWidgetFormTextarea(array(),array('style'=>'width:200px'));
  	              $this->widgetSchema['seo_keyword'] = new sfWidgetFormTextarea(array(),array('style'=>'width:200px'));
		 	
		 }		
		 ///
		
		  ////Контактная информация
		 if(sfConfig::get('app_use_contact_face')==true)
		 {
		 	$this->widgetSchema['separator_1'] =  new sfWidgetSeparator(array(),array('title'=>'Контактное лицо'));
		 	$this->widgetSchema['contact_fio'] = new sfWidgetFormInput(array(),array('size'=>'60')); 
		 	$this->widgetSchema['contact_dolzhnost'] = new sfWidgetFormInput(array(),array('size'=>'60'));
		 	$this->widgetSchema['contact_email'] =  new sfWidgetFormInput(array(),array('size'=>'60'));
		 	$this->widgetSchema['contact_phone'] = new sfWidgetFormInput(array(),array('size'=>'60'));
		 	
		 }		
		 ///
		 
		 
		  /////Карта проезда
		 if(sfConfig::get('app_use_code_map')==true)
		 {
		 	$this->widgetSchema['code_location'] =  new sfWidgetFormTextarea();
		 	$this->widgetSchema['custom_file1'] = new inputImageTag (  array (), array('mat_id'=>$this->object->getId(),'folder'=>'company') );
		 }
		 ////
		 
		  /////Статус ссылки
		 if(sfConfig::get('app_use_status_link')==true)
		 {
		 	$this->widgetSchema['custom_int2'] =  new sfWidgetFormChoice ( array ('choices' => array ('1' => 'активная', '2' => 'неактивная' ) ) );
		 }
		 ////
		 
		  /////Скидка
		 if(sfConfig::get('app_use_procent_bonus')==true)
		 {
		 	$this->widgetSchema['custom_int1'] =  new sfWidgetFormInput(array(),array('size'=>'6'));
		 }
		 ////
		 
		  /////Фотогалерея
		 if(sfConfig::get('app_use_gallery')==true)
		 {
		 	$this->widgetSchema['mat2image'] =  new inputMat2ImageTag (  array (), array('mat_id'=>$this->object->getId(),'folder'=>'gallery') );
		 }
		 ////
		 
		 /////Спецпредложение
		 if(sfConfig::get('app_use_cpecial_propose')==true)
		 {
		 	$this->widgetSchema['custom_text1'] =  new sfWidgetFormTextareaNickEdit ( array (), array ('class' => 'material_custom_text1', 'style' => 'width:650px' ) );
		 }
		 ////
		 
		  /////Рекомендации
		 if(sfConfig::get('app_use_recomendacii')==true)
		 {
		 	$this->widgetSchema['custom_text2'] =  new sfWidgetFormTextareaNickEdit ( array (), array ('class' => 'material_custom_text2', 'style' => 'width:650px' ) );
		 }
		 ////
		 
		  /////Купон на скидку
		 if(sfConfig::get('app_use_kupon')==true)
		 {
		 	$this->widgetSchema['custom_text3'] =  new sfWidgetFormTextareaNickEdit ( array (), array ('class' => 'material_custom_text3', 'style' => 'width:650px' ) );
		 }
		 ////	

		  /////Ссылка на форум
		 if(sfConfig::get('app_use_link_forum')==true)
		 {
		 	$this->widgetSchema['custom_char3'] =  new sfWidgetFormInput(array(),array('size'=>'60'));
		 }
		 ////	
		
		 		  /////Теги
		 if(sfConfig::get('app_use_tag')==true and $this->getObject()->getId()>0)
		 {
		 	$this->widgetSchema['tag'] =   new sfWidgetFormTextarea();
		 }
		 ////
		 
		
	    if(sfConfig::get('app_use_simple_region')==true)
	    {
	    	
	       $this->widgetSchema['region_id'] =  new sfWidgetFormPropelChoice(array('multiple' => false, 'expanded' => true, 'model' => 'Region', 'add_empty' => false));
	    }
		
		$this->widgetSchema->setLabels ( array ('title' => 'Наименование', 
		'separator_1'    => ' ',
  		'separator_2'    => ' ',
  		'separator_3'    => ' ',
  		'contact_fio'    => 'ФИО:', 
		'code_location'    => 'Код карты проезда:', 
  		'contact_dolzhnost'    => 'Должность:', 
  		'contact_email'    => 'e-mail:', 
  		'contact_phone'    => 'Телефон:', 
		'fax'    => 'Факс:', 
  		'link'    => 'Адрес сайта:',		
		'photo_path' => 'Логотип:', 
		'mat2image' => 'Фотогаллерея:',
		'custom_file1' => 'Фон:', 
		'custom_text1' => 'Спецпредложение:',
		'custom_text2' => 'Рекомендации:',
		'custom_text3' => 'Купон а скидку:',
		'see' => 'Просмотров:', 
		'content' => 'Описание предприятия:', 
		'seo_title' => 'SEO заголовок:', 
		'seo_keyword' => 'SEO слова для поиска:', 
		'mat2_folder_list' => 'Выбранные каталоги:', 
		'custom_int1' => 'Скидка:', 
		'custom_char1' => 'Короткое наименование:', 
		'custom_file1' => 'Файл карты проезда:',
		'adres' => 'Адрес:', 
		'phone' => 'Телефоны:', 
		'email' => 'E-mail:', 
		'custom_int2' => 'Статус ссылки:', 
		'pub' => 'Опубликован:', 
		'region_id'   => 'Регион:',
		'rating'   => 'Рейтинг:',
		'city'   => 'Город:',
		'custom_int3'   => 'Пакет услуг: ',
		'custom_char3'   => 'Ссылка на форум: ',
		'tag'   => 'Теги:',
		'short_content' => 'Примечание:' ) );
		
		$this->validatorSchema ['photo_path'] = new sfValidatorFile ( array ('required' => false, 
		'path' => sfConfig::get ( 'sf_web_dir' ) . '/uploads/material/company', 
		'mime_types' => 'web_images', 'max_size' => 500000, // 360 kB
         ) );
		
		$this->validatorSchema ['custom_file1'] = new sfValidatorFile ( array ('required' => false, 
		'path' => sfConfig::get ( 'sf_web_dir' ) . '/uploads/material/company', 
		'mime_types' => 'web_images', 'max_size' => 500000, // 360 kB
        'validated_file_class' => 'sfMatCompanyValidatedFile' ) );
		
		
		$this->validatorSchema['title'] = new sfValidatorString(array('required' => false),array('required'=>'поле обязательно'));
		
		/////////////////Обязательные поля///////////////////
	     /////Email
		 if(sfConfig::get('app_req_form1_email')==true)
		 {
		 	$this->validatorSchema['email'] = new sfValidatorString(array('required' => false),array('required'=>'поле обязательно'));
		 }
		 /// Контактный телефон
	      if(sfConfig::get('app_req_form1_phone')==true)
		 {
		 	$this->validatorSchema['phone'] = new sfValidatorString(array('required' => false),array('required'=>'поле обязательно'));
		 }		
		 /// Адрес
	      if(sfConfig::get('app_req_form1_adres')==true)
		 {
		 	$this->validatorSchema['adres'] = new sfValidatorString(array('required' => false),array('required'=>'поле обязательно'));
		 }	
		 /// Город
	      if(sfConfig::get('app_req_form1_city')==true)
		 {
		 	$this->validatorSchema['city'] = new sfValidatorString(array('required' => false),array('required'=>'поле обязательно'));
		 }		
			 /// Город
	      if(sfConfig::get('app_req_form1_content')==true)
		 {
		 	$this->validatorSchema['content'] = new sfValidatorString(array('required' => false),array('required'=>'поле обязательно'));
		 }		 	 
		 
		$this->widgetSchema->setNameFormat ( 'material[%s]' );
		
		$this->validatorSchema->setOption ( 'allow_extra_fields', true );
		
	
	}
	

	
	public function saveMat2FolderList($con = null) {
		
		if (! $this->isValid ()) {
			throw $this->getErrorSchema ();
		}
		
		if (! isset ( $this->widgetSchema ['mat2_folder_list'] )) {
			// somebody has unset this widget
			return;
		}
		
		if (is_null ( $con )) {
			$con = $this->getConnection ();
		}
		
		//$c = new Criteria ( );
		//$c->add ( Mat2FolderPeer::MATERIAL_ID, $this->object->getPrimaryKey () );
		//Mat2FolderPeer::doDelete ( $c, $con );
		
		$values = $this->getValue ( 'mat2_folder_list' );
		if (is_array ( $values )) {
			
			foreach ( $values as $value ) {
				
				$c = new Criteria();
				$c->add(Mat2FolderPeer::MATERIAL_ID,$this->object->getPrimaryKey ());
				$c->add(Mat2FolderPeer::FOLDER_ID,$value);
				$cnt = Mat2FolderPeer::doCount($c);
				
				if($cnt==0)
				{
				$obj = new Mat2Folder ( );
				$obj->setMaterialId ( $this->object->getPrimaryKey () );
				$obj->setFolderId ( $value );
				$obj->save ();
				
				$f = FolderPeer::retrieveByPK ( $value );
				if($this->getObject()->getId()>0 and !$f->isRoot())
				FolderPeer::setTags($value,$this->object->getPrimaryKey ());
				
				
				if ($f->hasParent ()) {
					$par = $f->retrieveParent ();
					
					if (! in_array ( $par->getId (), $values )) {
						
						$this->saverec ( $par, $this->object->getPrimaryKey () );
						////Добавляем счетчик
				       
						if ($par->hasParent ()) {
							$parr = $par->retrieveParent ();
							
							if (! in_array ( $parr->getId (), $values )) {
								//print_r($values).'-'.$parr->getId();
						         ////Добавляем счетчик
				                							

								$this->saverec ( $parr, $this->object->getPrimaryKey () );
								if ($parr->hasParent ()) {
									$parrr = $parr->retrieveParent ();
									if (! in_array ( $parrr->getId (), $values )) {
										$this->saverec ( $parrr, $this->object->getPrimaryKey () );
						                ////Добавляем счетчик
				                      							
									}
								}
							
							}
						
						}
					}
				
				}
			
			}
			}
		}
	}
	
	public function saverec($par, $mat_id) {
		
		//echo $par->getId().'-'.$mat_id;
		
		$c = new Criteria ( );
		$c->add ( Mat2FolderPeer::FOLDER_ID, $par->getId () );
		$c->addAnd ( Mat2FolderPeer::MATERIAL_ID, $mat_id );
		$cnt = Mat2FolderPeer::doCount ( $c );
		if ($cnt == 0) {
			$re = new Mat2Folder ( );
			$re->setMaterialId ( $mat_id );
			$re->setFolderId ( $par->getId () );
			$re->save ();
			
		}
	
	}
	
function myFormatter($widget, $inputs)
  {
  	$str= '';
    $str = get_partial('checked_folders',array('arr'=>$this['mat2_folder_list']->getValue(),'scope_id'=>sfConfig::get('app_scope_org'))).'<b>Каталог</b>'.get_component('zdFolder','show_folders',array('arr'=>$this['mat2_folder_list']->getValue(),'folder_id'=>sfConfig::get('app_folder_org'),'width_check'=>'yes'));
    //$str = '<b>Регионы</b>'.get_partial('checked_folders',array('form'=>$this,'scope_id'=>sfConfig::get('app_scope_region'))).get_component('zdFolder','show_folders',array('folder_id'=>sfConfig::get('app_folder_region'),'width_check'=>'yes'));
   if(sfConfig::get('app_use_region')==true)
	    {
	      $str .= '<b>Регионы</b>'.get_component('zdFolder','show_folders',array('arr'=>$this['mat2_folder_list']->getValue(),'folder_id'=>sfConfig::get('app_folder_region'),'width_check'=>'yes'));	
	    }
    return $str;
  }	
  
  
}
